package com.jrh.web.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jrh.biz.feature.FeatureService;
import com.jrh.common.constant.JrhBizConstant;
import com.jrh.common.json.JacksonHelper;
import com.jrh.dal.CategoryDao;
import com.jrh.domain.entity.Feature;

@Controller
@RequestMapping("/admin/feature/")
public class AdminFeatureController {

    @Autowired
    private CategoryDao    categoryDao;
    @Autowired
    private FeatureService featureService;

    @RequestMapping("list")
    public String list(Integer pageIndex, String categoryId, Model model) {
        if (pageIndex == null) {
            pageIndex = 1;
        }
        model.addAttribute("pageData",
                           featureService.listFeatureByCondition(categoryId, pageIndex, JrhBizConstant.SIZE_PER_PAGE));
        model.addAttribute("categorys", categoryDao.listAllCategory());
        model.addAttribute("categoryId", categoryId);
        return "admin/feature/list";
    }

    @RequestMapping(method = RequestMethod.POST, value = "create")
    public String create(Feature feature) {
        featureService.createFeature(feature);
        return "redirect:/admin/feature/list";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "delete/{id}")
    public String delete(@PathVariable long id) {
        featureService.deleteFeature(id);
        return Boolean.TRUE.toString();
    }

    @RequestMapping(method = RequestMethod.GET, value = "update/{id}")
    public String update(@PathVariable long id, Model model) {
        Feature feature = featureService.getFeatureById(id);
        model.addAttribute("categorys", categoryDao.listAllCategory());
        model.addAttribute("feature", feature);
        return "admin/feature/update";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String doUpdate(Feature feature) {
        featureService.updateFeature(feature);
        return "redirect:/admin/feature/list";
    }

    @ResponseBody
    @RequestMapping(value = "finc/{categoryId}/{productId}")
    public String listFeatureInCategory(@PathVariable String categoryId, @PathVariable String productId) {
        List<Feature> featureList = featureService.listFeatureDetailByCatAndProd(categoryId, productId);
        return JacksonHelper.toJSON(featureList);
    }

}
